package com.sunny.myproject.produce.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sunny.myproject.core.base.action.BaseAction;
import com.sunny.myproject.core.base.util.LoginUtil;
import com.sunny.myproject.produce.entity.Bom;
import com.sunny.myproject.produce.entity.Bom_sub;
import com.sunny.myproject.produce.service.BomService;
import com.sunny.myproject.produce.service.Bom_subService;
import com.sunny.myproject.storem.entity.Materiel;
import com.sunny.myproject.storem.service.MaterielService;

@Controller
@RequestMapping("/produce/bom")
public class BomAction extends BaseAction<Bom>{

	private String title = "BOM";
	private String action ="produce/bom";
	private String function = "bom";
	
	private Logger logger = Logger.getLogger(BomAction.class);
	
	@Autowired
	private BomService service;
	
	@Autowired
	private Bom_subService bom_subService;
	
	@Autowired
	private MaterielService materielService;
	
	@Override
	@RequestMapping(params="list")
	public String list(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			super.pager = super.pageStart(model, request, response, action, function, title);
			super.pager = super.pageEnd(model, service.num(criterions), pager);
			super.returnValue(model, service.find(criterions, pager));
		} catch (Exception e) {
			logger.error(e);
		}
		return "produce/bomList";
	}

	@Override
	@RequestMapping(params="add")
	public String add(HttpServletRequest request, HttpServletResponse response) {
		super.add(title, request);
		return "produce/bomEdit";
	}

	@Override
	@RequestMapping(params="edit")
	public String edit(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			Bom bom = service.findById(super.edit(title, model, request));
			
			logger.warn("判断是否审核");
			if(bom.getStatus().equals("已审批")){
				logger.info("已审核，处理");
				LoginUtil.error_forward(response, request, "已审核不能修改", "produce/bom?list");
			}
			super.returnValue(model, bom);
			@SuppressWarnings("unchecked")
			List<Bom_sub> bom_subs = (List<Bom_sub>) service.queryHql("from Bom_sub where bom.id="+bom.getId());
			logger.info("bom_subs list size:"+bom_subs.size());
			for (Bom_sub bom_sub : bom_subs) {
				Materiel materiel = materielService.findById(bom_sub.getMateriel().getId());
				logger.info("materiel_id:"+materiel.getId());
				bom_sub.setMateriel(materiel);
			}
			model.addAttribute("bom_sub", bom_subs);
		} catch (Exception e) {
			logger.error(e);
		}
		return "produce/bomEdit";
	}
	@Override
	@RequestMapping(params="delete")
	public String delete(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			bom_subService.queryBulkUpdate("delete from Bom_sub where bom="+super.param1(request));
			service.deleteByIds(super.param2(request));
		} catch (Exception e) {
			logger.error(e);
		}
		return "redirect:/produce/bom?list";
	}

	@Override
	@RequestMapping(params="save")
	public String save(HttpServletRequest request,
			HttpServletResponse response, Bom t) {
		try {
			service.save(t);
			String[] materiel_id_str = request.getParameterValues("bom_sub.materiel.id");
			logger.info("materiel_id_str.length:"+materiel_id_str.length);
			String[] amount_str = request.getParameterValues("bom_sub.amount");
			logger.info("amount_str.length:"+amount_str.length);
			String[] loss_str = request.getParameterValues("bom_sub.loss");
			String[] location_str = request.getParameterValues("bom_sub.location");
			String[] makeCode_str = request.getParameterValues("bom_sub.makeCode");
			String[] bomlevel_str = request.getParameterValues("bom_sub.bomlevel");
			
			String[] bom_sub_id = request.getParameterValues("bom_sub.id");
			
			for(int i=0;i<materiel_id_str.length;i++){
				logger.info("materiel_id_str[i]:"+materiel_id_str[i]);
				Materiel materiel = new Materiel();
				materiel.setId(Long.parseLong(materiel_id_str[i]));
				
				Bom_sub bom_sub = new Bom_sub();
				bom_sub.setAmount(Double.parseDouble(amount_str[i]));
				bom_sub.setBom(t);
				bom_sub.setBomlevel(Integer.parseInt(bomlevel_str[i]));
				bom_sub.setLoss(Double.parseDouble(loss_str[i]));
				bom_sub.setLocation(location_str[i]);
				bom_sub.setMakeCode(makeCode_str[i]);
				bom_sub.setBomlevel(Integer.parseInt(bomlevel_str[i]));
				bom_sub.setMateriel(materiel);
				
				if(bom_sub_id!=null&&bom_sub_id.length!=0&&!bom_sub_id[i].equalsIgnoreCase(""))
					bom_sub.setId(Long.parseLong(bom_sub_id[i]));
				bom_subService.save(bom_sub);
			}
			
			//删除没有的bom_sub.id
			StringBuffer str_bom_id = new StringBuffer();
			for (String string : bom_sub_id) {
				str_bom_id.append(string+",");
			}
			String temp= str_bom_id.length()>0?str_bom_id.substring(0, str_bom_id.length()-1):"";
			bom_subService.queryBulkUpdate("delete from Bom_sub where id not in" +
					"("+temp+") and bom.id="+t.getId());
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return "redirect:/produce/bom?list";
	}

	@Override
	@RequestMapping(params="view")
	public String view(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			Bom bom = service.findById(super.view(title, model, request));
			super.returnViewValue(model, bom);
			@SuppressWarnings("unchecked")
			List<Bom_sub> bom_subs = (List<Bom_sub>) service.queryHql("from Bom_sub where bom.id="+bom.getId());
			logger.info("bom_subs list size:"+bom_subs.size());
			for (Bom_sub bom_sub : bom_subs) {
				Materiel materiel = materielService.findById(bom_sub.getMateriel().getId());
				logger.info("materiel_id:"+materiel.getId());
				bom_sub.setMateriel(materiel);
			}
			model.addAttribute("bom_sub", bom_subs);
		} catch (Exception e) {
			logger.error(e);
		}
		return "produce/bomEdit";
	}

	@RequestMapping(params="approval")
	public String approval(Model model, HttpServletRequest request,
			HttpServletResponse response){
		logger.info("approval");
		try {
			Bom bom = service.findById(super.param1(request));
			bom.setStatus("已审批");
			service.save(bom);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return "redirect:/produce/bom?list";
	}
	
	@RequestMapping(params="query")
	public String query(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			super.pager = super.pageStart(model, request, response, action, function, title);
			super.pager = super.pageEnd(model, service.num(criterions), pager);
			criterions.add(Restrictions.eq("status", "已审批"));
			super.returnValue(model, service.find(criterions, pager));
		} catch (Exception e) {
			logger.error(e);
		}
		return "produce/bomQuery";
	}
}
